package com.drool.mediaplayer;

import com.drool.mediaplayer.Adapters.AudioFreqListAdapter;
import com.drool.mediaplayer.Database.MediaFilesDB;
import com.drool.mediaplayer.Database.MediaFilesDBHelper;
import com.drool.mediaplayer.Database.WritableDatabase;
import com.drool.mediaplayer.Extracter.AudioInfoExtracter;
import com.drool.mediaplayer.Extracter.VideoInfoExtracter;
import com.drool.mediaplayer.services.DroolService;
import com.drool.mediaplayer.services.IRemoteInterface;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore.Audio;
import android.provider.MediaStore.Video;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;


public class MediaLibrary extends Activity {
	
	private static final String TAG = "Drool:MediaLibrary";
	
	public static final String TYPE = "type";
	public static final int MUSIC = 1;
	public static final int VIDEO = 2;
	public static int customContext = 0;
	public static final int musicContext = 1;
	public static final int videoContext = 2;
	
	Button videoButton, showMusicButton, showVideoButton;
	ImageButton songsButton, albumsButton;
	ViewFlipper flipper;
	private MediaFilesDBHelper myDBHelper;	
	private SQLiteDatabase db;
	
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		
		db.close();
		myDBHelper.close();
		super.onStop();		
	}

	
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		myDBHelper = new MediaFilesDBHelper(MediaLibrary.this);	
		db = myDBHelper.getReadableDatabase();
		
		final Intent intent = new Intent(MediaLibrary.this.getApplicationContext(), 
				MediaLibraryBrowser.class);

		final Intent songIntent = new Intent(MediaLibrary.this.getApplicationContext(), 
				SongAlbumBrowser.class);
		
		albumsButton = (ImageButton)findViewById(R.id.albumsButton);
		albumsButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				intent.putExtra(TYPE, MUSIC);
				startActivity(intent);
			}
		});
		
		songsButton = (ImageButton)findViewById(R.id.songsButton);
		songsButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				/*
				songIntent.putExtra(SongAlbumBrowser.SELECTION, SongAlbumBrowser.SELECTION_ALL);
				startActivity(songIntent);
				*/
				finish();
			}
		});
		
		
		//use a selector drawable
		
		videoButton = (Button)findViewById(R.id.videoButton);
		videoButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				intent.putExtra(TYPE, VIDEO);
				startActivity(intent);
			}
		});

		
		flipper = (ViewFlipper)findViewById(R.id.detailsFlipper);
		flipper.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));
		flipper.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
		
		showMusicButton = (Button)findViewById(R.id.showMusicButton);
		
		showMusicButton.setOnClickListener(new View.OnClickListener() {				
				@Override
				public void onClick(View arg0) {					
					flipper.showNext();
				}
			});
		
		showVideoButton = (Button)findViewById(R.id.showVideoButton);
		
		showVideoButton.setOnClickListener(new View.OnClickListener() {				
				@Override
				public void onClick(View arg0) {					
					flipper.showNext();
				}
			});
		
		showInfo();
		setupFlipper();
		updateLibrary();
		
		super.onStart();  
	}



	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		Log.d("Sudeep", "Shuting down the activity");
	}



	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.laymedialib);
		
		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
		{
			Log.i(TAG, "SD Card Present");
		}
		else
		{	
			Log.i(TAG, "SD Card NOT Present");
			Toast.makeText(this, "SD Card not Present! Please Insert a new one",Toast.LENGTH_LONG).show();
			finish();		
		}
		
	    SharedPreferences settings = getSharedPreferences(MyPreferences.PREFERENCE_NAME,0);
		SharedPreferences.Editor prefEditor = settings.edit();
		prefEditor.putString(MyPreferences.MPSTATE, MyPreferences.MPSTATE_VALUE_INIT);
		prefEditor.putLong(MyPreferences.ACTIVE_PLAYLIST, -1);
		prefEditor.putInt(MyPreferences.LOOP_STATE, MyPreferences.LOOP_STATE_VALUE_OFF);
		prefEditor.putInt(MyPreferences.SHUFFLE_STATE, MyPreferences.SHUFFLE_STATE_VALUE_OFF);
		prefEditor.commit();
	}
	
	private void updateLibrary(){ 
		WritableDatabase wDB = new WritableDatabase(this);
		
		AudioInfoExtracter aExtracter = new AudioInfoExtracter();
		VideoInfoExtracter vExtracter = new VideoInfoExtracter();
		
		aExtracter.mCursorAudio = managedQuery(aExtracter.mMedia, aExtracter.projection, null, null,Audio.Media.DATE_ADDED + " ASC");
		startManagingCursor(aExtracter.mCursorAudio);
		
		if (aExtracter.mCursorAudio.getCount()> 0)
		{
			aExtracter.mCursorAudio.moveToFirst();
			while (aExtracter.mCursorAudio.isAfterLast() == false )
			{		
				if (itemNew(MediaFilesDB.FileHeader.HDR_TABLE_NAME,MediaFilesDB.FileHeader.HDR_FILE_NAME,
						aExtracter.mCursorAudio.getString(1))){
					//notify user of new item
					Log.i(TAG, "New Audio Found - " + aExtracter.mCursorAudio.getString(1));
					/*
					AlertDialog ad = new AlertDialog.Builder(MediaLibraryBrowser.this)						
						//.setIcon(R.drawable.icon)
						.setMessage("New Music has been found on your SD Card. Would you like to update the library?")
						.setTitle("Yae..New Music found!!")
						.setPositiveButton("Yes!", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {																										
									wDB.updateAudioLib(MediaLibraryBrowser.this);										
								}                
							})
						.setNegativeButton("Not Now!", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {									
								//TODO Write code for Cancel dialog
								}                
							}).show();
					*/	
					wDB.updateAudioLib(MediaLibrary.this);
					break;
				}
				aExtracter.mCursorAudio.moveToNext();
			}				
		}else
			Log.i(TAG, "No Audio files found on SD card");
		aExtracter.mCursorAudio.close();
		Log.i(TAG, "End of parent if");
		
		vExtracter.mCursorVideo = managedQuery(vExtracter.mMedia, vExtracter.projection, null, null,Video.Media.DATE_ADDED + " ASC");
		startManagingCursor(vExtracter.mCursorVideo);
		
		if (vExtracter.mCursorVideo.getCount()> 0)
		{
			vExtracter.mCursorVideo.moveToFirst();
			while (vExtracter.mCursorVideo.isAfterLast() == false )
			{		
				if (itemNew(MediaFilesDB.FileHeader.HDR_TABLE_NAME,MediaFilesDB.FileHeader.HDR_FILE_NAME,
						vExtracter.mCursorVideo.getString(1))){
					//notify user of new item
					Log.i(TAG, "New Video Found - " + vExtracter.mCursorVideo.getString(1));
					wDB.updateVideoLib(MediaLibrary.this);
					break;
				}
				vExtracter.mCursorVideo.moveToNext();
			}
			vExtracter.mCursorVideo.close();
		}
	}
	
	private boolean itemNew(String tableName, String tableCol, String item)
	{
		//MediaFilesDBHelper myDBHelper = new MediaFilesDBHelper(MediaLibrary.this);	
		//SQLiteDatabase db = myDBHelper.getReadableDatabase();		
		Cursor c = db.query(tableName,new String[] {tableCol} ,
				tableCol + " =?", 
				new String[] {item}, null, null, null);
		
		if (c.getCount()==0){
			c.close();
			return true;
		}
		else{
			c.close();
			return false;			
		}		
	}
	
	private void setupFlipper(){
		//TODO update the flipper data based on changes in the database realtime
		ViewFlipper flipper;
		ListView mFreqList;
		final Cursor freqCursor;
		Cursor vfreqCursor;
		TextView txt;
		//MediaFilesDBHelper myDBHelper = new MediaFilesDBHelper(MediaLibrary.this);
				
		//flipper = (ViewFlipper)findViewById(R.id.mAutoFlipper);
		
		mFreqList = (ListView)findViewById(R.id.mFreqList);
		
		
		
		//SQLiteDatabase db = myDBHelper.getReadableDatabase(); 
		
		freqCursor = db.query(MediaFilesDB.FileHeader.HDR_TABLE_NAME + "," 
				+ MediaFilesDB.AudioFiles.AUDIO_TABLE_NAME,
				new String[] {MediaFilesDB.FileHeader.HDR_TABLE_NAME + "." + MediaFilesDB.FileHeader._ID + " as _id",				
							  MediaFilesDB.FileHeader.HDR_FILE_NAME,
							  MediaFilesDB.AudioFiles.AUDIO_DURATION},
				MediaFilesDB.AudioFiles.AUDIO_NUM_OF_TIMES + " > 0"
				+ " and " + MediaFilesDB.FileHeader.HDR_TABLE_NAME + "." + MediaFilesDB.FileHeader.HDR_FILE_ID
				+ "=" + MediaFilesDB.AudioFiles.AUDIO_TABLE_NAME + "." + MediaFilesDB.AudioFiles._ID
				+ " and " + MediaFilesDB.FileHeader.HDR_FILE_TYPE + "=\'a\'",
				null, null, null,MediaFilesDB.AudioFiles.AUDIO_NUM_OF_TIMES + " Desc" );
		
		startManagingCursor(freqCursor);
		 
		Log.i(TAG, "mfreqcur " + freqCursor.toString());
		if (freqCursor.getCount()> 0){
			Log.i(TAG, "Setting up the freq list adapater now");
			/*
			ListAdapter adapter = new SimpleCursorAdapter(
					this, R.layout.layfreqlistitem,
				    freqCursor, new String[] {
						MediaFilesDB.FileHeader.HDR_FILE_NAME,
					}, new int[] {R.id.FreqItemtxt}
			);
			*/
			
			AudioFreqListAdapter adapter = new AudioFreqListAdapter(MediaLibrary.this, freqCursor);
			
			mFreqList.setAdapter(adapter);
			
			mFreqList.setOnItemClickListener(new OnItemClickListener(){

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int position, long arg3) {
					Uri audio = Audio.Media.EXTERNAL_CONTENT_URI;				
					
					freqCursor.moveToPosition(position);
					
					Cursor aCursor = managedQuery(audio,new String [] {
							Audio.Media._ID, Audio.Media.ALBUM_ID},
							Audio.Media.TITLE + "=" +"\"" + freqCursor.getString(freqCursor.getColumnIndex(
									MediaFilesDB.FileHeader.HDR_FILE_NAME)) + "\"" ,null,null);
					startManagingCursor(aCursor);
					
					
					if (aCursor.getCount() > 0){
						aCursor.moveToFirst();
						Intent intent = new Intent(MediaLibrary.this, 
								MediaPlayerActivity.class);
						
						intent.putExtra(MediaPlayerActivity.TYPE,MediaPlayerActivity.SONG);
						intent.putExtra(MediaPlayerActivity.DATA, aCursor.getString(0));
						intent.putExtra(MediaPlayerActivity.DATA1, aCursor.getString(1));
						startActivity(intent);
					}else{
						Log.e(TAG, "Song not found");
					}
					
				}
				
			});
			
		}	
		
		
		vfreqCursor = db.query(MediaFilesDB.FileHeader.HDR_TABLE_NAME + "," 
				+ MediaFilesDB.VideoFiles.VIDEO_TABLE_NAME,
				new String[] {MediaFilesDB.FileHeader.HDR_TABLE_NAME + "." + MediaFilesDB.FileHeader._ID + " as _id",				
							  MediaFilesDB.FileHeader.HDR_FILE_NAME},
				MediaFilesDB.VideoFiles.VIDEO_NUM_OF_TIMES + " > 0"
				+ " and " + MediaFilesDB.FileHeader.HDR_TABLE_NAME + "." + MediaFilesDB.FileHeader.HDR_FILE_ID
				+ "=" + MediaFilesDB.VideoFiles.VIDEO_TABLE_NAME + "." + MediaFilesDB.VideoFiles._ID
				+ " and " + MediaFilesDB.FileHeader.HDR_FILE_TYPE + "=\'v\'",
				null, null, null,MediaFilesDB.VideoFiles.VIDEO_NUM_OF_TIMES + " Desc" );
		
		startManagingCursor(vfreqCursor);
		
		Log.i(TAG, "mfreqcur " + vfreqCursor.toString());
		
		mFreqList = (ListView)findViewById(R.id.vFreqList);
		txt = (TextView)findViewById(R.id.vFreqLabel);
		txt.setText("Most frequently played videos");
		
		vfreqCursor.moveToFirst();
		
		
		//Log.i(TAG, Integer.toString(vfreqCursor.getCount()) + vfreqCursor.getString(1));	
			
		if (vfreqCursor.getCount()> 0){
			Log.i(TAG, "Setting up the freq list adapater now");
			ListAdapter vAdapter = new SimpleCursorAdapter(
					this, R.layout.layfreqlistitem,
				    vfreqCursor, new String[] {
						MediaFilesDB.FileHeader.HDR_FILE_NAME,
					}, new int[] {R.id.FreqItemtxt}
			);
			
			mFreqList.setAdapter(vAdapter);		
		}
		
	}
	
	private void showInfo(){
		
		Cursor songCursor, albumCursor, videoCursor;
		TextView txt;
		
		Uri audio = Audio.Media.EXTERNAL_CONTENT_URI;
		Uri albums = Audio.Albums.EXTERNAL_CONTENT_URI;
		Uri video = Video.Media.EXTERNAL_CONTENT_URI;
		
		
		songCursor = managedQuery(audio,new String [] {
				Audio.Media._ID},
				null,null,null);
		
		albumCursor = managedQuery(albums,new String [] {
				Audio.Albums._ID},
				null,null,null);
		
		videoCursor = managedQuery(video, new String [] {
				Video.Media._ID},
				null, null,null);
		
		txt = (TextView) findViewById(R.id.mInfoLabel);
		txt.setText("You have " + Integer.toString(songCursor.getCount())+ " songs in " + Integer.toString(albumCursor.getCount()) + " albums");
		
		txt = (TextView)findViewById(R.id.vInfoLabel);
		txt.setText("You have " + Integer.toString(videoCursor.getCount()) + " videos");
		songCursor.close();
		albumCursor.close();
		videoCursor.close();
		
	}
}


